package com.wpw.web.work.batchrefit;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @ClassName: RefitExctor
 * @CreateDate: 2020-06-14 10:15
 * @author: wupengwei
 */
public class RefitExctor {

    private static final int CORE_POOL_SIZE = 5;
    private static final int MAX_POOL_SIZE = 10;
    private static final int QUEUE_CAPACITY = 100;
    private static final Long KEEP_ALIVE_TIME = 1L;

    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAX_POOL_SIZE,
            KEEP_ALIVE_TIME,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(QUEUE_CAPACITY),
            new NamedThreadFactory("buyAndSell-refit"),
            new ThreadPoolExecutor.CallerRunsPolicy());

    public static void excuteRefitBuyAndSell(List<String> tool) {

        CountDownLatch countDownLatch = new CountDownLatch(tool.size());

        for (String code : tool) {

            System.out.println("准备工作");
            String a = code + "开始执行了";
            executor.submit(() -> {
                System.out.println(a);
                try {
                    Thread.sleep(3000);
                    System.out.println(code + "执行完:" + Thread.currentThread().getName());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }

            });
        }

        try {

            long start = System.currentTimeMillis();
            System.out.println("主线程开始等待");
            countDownLatch.await(10, TimeUnit.SECONDS);
            System.out.println("结束，耗时" + (System.currentTimeMillis() - start) + "ms");

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            executor.allowCoreThreadTimeOut(true);;
        }
    }

    public static void main(String[] args) {
        List<String> tools = new ArrayList<>();
        tools.add("第一个");
        tools.add("第二个");
        tools.add("第三个");


        RefitExctor.excuteRefitBuyAndSell(tools);

        List<String> tools2 = new ArrayList<>();
        tools2.add("第三个");
        tools2.add("第4个");
        tools2.add("第5个");
        RefitExctor.excuteRefitBuyAndSell(tools2);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        List<String> tools3 = new ArrayList<>();
        tools3.add("第7个");
        tools3.add("第8个");
        tools3.add("第9个");
        RefitExctor.excuteRefitBuyAndSell(tools3);
    }


}